import { connect } from 'dva';
import { Component } from 'react';
import { Spin, Pagination } from 'antd';
import { routerRedux } from 'dva/router';
import PostsItem from './PostsItem';
import CommentModal from './CommentModal';

class Posts extends Component {
    constructor(props) {
        super(props);
        this.state = {
            users: props.users,
            list: props.list,
            total: props.total,
            page: props.page,
            loading: false,
            commentVisible: false,
            comments: props.comments,
        }
    }

    static getDerivedStateFromProps = (nextProps, prevState) => {
        return nextProps;
    }

    showCommnetModal = ( id ) => {
        this.props.dispatch({
            type: 'posts/getComments',
            payload: { id },
          });
        this.setState({
            commentVisible: true,
        });
    }
    hideCommnetModal = ( id ) => {
        this.setState({
            commentVisible: false,
        });
    }

    pageChangeHandle = ( page, pageSize ) => {
        this.props.dispatch(routerRedux.push({
            pathname: '/posts',
            query: { page },
        }));
    }

    render() {
        const { users, list, total, page, loading } = this.state;
        return (
            <div>
                <Spin spinning={ loading }>
                {
                    list.map( ( v, i ) => {
                        if( users === undefined ){
                            v.userName = 'loading';
                        }else{
                            v.userName = users[ v.userId - 1 ].name;
                        }
                        return (
                            <PostsItem
                                key={ i }
                                info={ v }
                                showComment={ ( id ) => this.showCommnetModal( id ) }
                            />
                        );
                    })
                }
                </Spin>
                <Pagination
                    current={ page }
                    total={ total }
                    onChange={ this.pageChangeHandle }
                />
                <CommentModal
                    visible={ this.state.commentVisible }
                    comments={ this.state.comments }
                    hideComment={ ( id ) => this.hideCommnetModal( id ) }
                />
            </div>
        );
    }
}

const mapStateToProps = (state) => {
    const { users, list, total, page, comments } = state.posts;
    return {
        users,
        list,
        total,
        page,
        comments,
        loading: state.loading.models.posts,
    };
}
// export default Posts;
export default connect(mapStateToProps)(Posts);